"use strict";

var express = require('express');
var UUID = require('uuid')
var dt = require('date-utils')
var util = require('util')
var MyUtils = require('./../util/utils')
var connection = require('./../constant/mysqlconnection').connection
var DeleteAction = require('./app/delete-app')

var router = express.Router();
var myUtils = new MyUtils()
var deleteAction = new DeleteAction()

router.use(function (req, res, next) {
    // todo 判断用户是否登陆
    next()
})

router.post('/createAppVersion', function (req, res, next) {
    var searchSql = 'select app.id , version.app_version_code,version.logic_delete_flag from application app left join appversion version on ' +
        'app.id = version.application_id where app.logic_delete_flag = 01 and app.id = ?'

    var searchSqlParams = [
        req.body.appId
    ]
    connection.query(searchSql, searchSqlParams, function (error, results) {
        if (!error) {
            var bizSucModel = myUtils.generateSuccess()
            if (results.length == 0) {
                bizSucModel.model = {
                    success: 1,
                    info: '请先创建应用再添加版本号'
                }
                res.end(JSON.stringify(bizSucModel))
            } else {
                if (isAllowCreateAppVersion(results, parseInt(req.body.appVersionCode))) {
                    // 允许创建
                    next('route')
                } else {
                    bizSucModel.model = {
                        success: 2,
                        info: '版本号不能重复，请重新输入版本号'
                    }
                    res.end(JSON.stringify(bizSucModel))
                }
            }
        } else {
            res.end(JSON.stringify(myUtils.generateInnerError()))
        }
    })
})

function isAllowCreateAppVersion(results, awaitCreateVersionCode) {
    for (var i = 0, len = results.length; i < len; i++) {
        if (results[i].app_version_code != null && results[i].app_version_code === awaitCreateVersionCode && results[i].logic_delete_flag === '01') {
            return false
        }
    }
    return true
}

router.post('/createAppVersion', function (req, res) {
    var insertSql = 'INSERT INTO appversion(id,app_version_name,app_version_code,application_id,create_time,logic_delete_flag) VALUES(?,?,?,?,?,\'01\')'
    var date = new Date().toFormat('YYYY-MM-DD HH24:MI:SS')
    var appVersionId = UUID.v1()
    var insertSqlParams = [
        appVersionId,
        req.body.appVersionName,
        req.body.appVersionCode,
        req.body.appId,
        date
    ]
    connection.query(insertSql, insertSqlParams, function (error, result) {
        if (!error) {
            var bizSucModel = myUtils.generateSuccess()
            bizSucModel.model = {
                success: 0,
                info: '创建成功',
                createTime: date,
                appVersionId: appVersionId
            }
            res.end(JSON.stringify(bizSucModel))
        } else {
            console.log(error)
            res.end(JSON.stringify(myUtils.generateInnerError()))
        }
    })
})


router.delete('/deleteAppVersion', function (req, res) {
    deleteAction.deleteAppVersion(req, res)
})

router.get('/appVersionList', function (req, res) {
    var searchSql = 'select id, app_version_name,app_version_code,create_time from appversion where logic_delete_flag = 01 and application_id = ? ORDER BY create_time DESC ' +
        'LIMIT ' + (parseInt(req.query.page) - 1) + ',' + req.query.size
    var searchSqlParams = [
        req.query.applicationId
    ]
    connection.query(searchSql, searchSqlParams, function (error, results) {
        if (!error) {
            var bizSucModel = myUtils.generateSuccess()
            bizSucModel.model = {
                success: 0,
                appVersionList: results
            }
            res.end(JSON.stringify(bizSucModel))
        } else {
            res.end(JSON.stringify(myUtils.generateInnerError()))
        }
    })
})

module.exports = router
